package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ExportDao;
import cn.itcast.dao.cargo.PackingDao;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.Packing;
import cn.itcast.domain.cargo.PackingExample;
import cn.itcast.service.cargo.PackingService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

// com.alibaba.dubbo.config.annotation.Service
@Service(timeout = 100000)
public class PackingServiceImpl implements PackingService {

    /* 注入装箱单信息*/
    @Autowired
    private PackingDao packingDao;

    @Autowired
    private ExportDao exportDao;

    @Override
    public PageInfo<Packing> findByPage(PackingExample packingExample, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Packing> list = packingDao.selectByExample(packingExample);
        return new PageInfo<>(list);
    }

    @Override
    public Packing findPackingByExport(String id) {
        //根据报运单id查找多个货物 计算体积 净重 毛重
        String[] split = id.split(",");
        //体积
        String exportNos = "";
        double totalVolum = 0;
        double netWeights = 0;
        double grossWeights = 0;

        for (int i = 0; i < split.length; i++) {
            Export export = exportDao.selectByPrimaryKey(split[i]);
            //拼接报运单的合同号
            exportNos += export.getCustomerContract();
            grossWeights += export.getGrossWeights();
            totalVolum += export.getMeasurements();
        }
        Packing packing = new Packing();
        packing.setExportIds(id);
        packing.setExportNos(exportNos);
        packing.setNetWeights(grossWeights-10>0?grossWeights-10:0);
        packing.setGrossWeights(grossWeights);
        packing.setTotalVolum(totalVolum);
        packing.setPackingMoney(grossWeights * 11);

        return packing;
    }

    @Override
    public Packing findById(String id) {
        return packingDao.selectByPrimaryKey(id);
    }

    @Override
    public void save(Packing packing) {
        packing.setPackingListId(UUID.randomUUID().toString());
        packing.setState((long) 0);
        packingDao.insertSelective(packing);
        String exportIds = packing.getExportIds();
        String[] strings = exportIds.split(",");
        if (strings != null && strings.length > 0) {
            for (String string : strings) {
                Export export = new Export();
                export.setId(string);
                export.setState(4);
                exportDao.updateByPrimaryKeySelective(export);
            }
        }
    }

    @Override
    public void update(Packing packing) {
        packingDao.updateByPrimaryKey(packing);
    }

    /*@Override
    public void save(Packing packing) {
        //1. 设置报运单id
        packing.setPackingListId(UUID.randomUUID().toString());

        //2. 获取购销合同的id，多个id用逗号隔开
        String contractIds = packing.getContractIds();
        if (contractIds == null) {
            throw new RuntimeException("购销合同的id为NULL，异常！");
        }

        //3. 处理报运单的合同号，数据来自于购销合同的合同号。多个合同号用空格隔开。
        String[] contractIdArray = contractIds.split(",");
        List<String> contractIdList = Arrays.asList(contractIdArray);
        // 根据购销合同的id查询
        ContractExample contractExample = new ContractExample();
        contractExample.createCriteria().andIdIn(contractIdList);
        List<Contract> contractList = contractDao.selectByExample(contractExample);
        // 保存报运单中的合同号，多个合同号用空格隔开
        String contractNos = "";
        if (contractList != null && contractList.size() > 0) {
            for (Contract contract : contractList) {// 123 45
                contractNos += contract.getContractNo() + " ";
                //4. 合同列表，选中的购销合同，生成报运单后，需求修改购销合同的状态为2，表示已生成报运
                contract.setState(2);
                contractDao.updateByPrimaryKeySelective(contract);
            }
        }
        // 设置报运单的合同号 (通过String类的trim()方法去掉前后空格)
        packing.setCustomerContract(contractNos.trim());


        //5. 根据购销合同，查询其下的所有货物
        ContractProductExample cpExample = new ContractProductExample();
        // select * from co_contract_product where contract_id in (1,2)
        cpExample.createCriteria().andContractIdIn(contractIdList);
        List<ContractProduct> contractProductList = contractProductDao.selectByExample(cpExample);
        // 创建一个map，key是货物id，value是商品id
        Map<String, String> idMap = new HashMap<>();
        //6. 【保存报运单的商品，数据来源于'购销合同的货物'】
        if (contractProductList != null && contractProductList.size() > 0) {
            for (ContractProduct contractProduct : contractProductList) {
                // 创建商品对象
                PackingProduct packingProduct = new PackingProduct();
                // 封装商品对象: 对象拷贝，导入org.springframework.beans
                // 注意：不要导错包，如果导入apache的包参数顺序刚好相反
                // 参数1：source，数据源，有数据的对象
                // 参数2：目标， 要拷贝到的目标对象
                BeanUtils.copyProperties(contractProduct, packingProduct);
                // 设置商品id
                packingProduct.setId(UUID.randomUUID().toString());
                // 设置商品关联的报运单id 【重要】
                packingProduct.setPackingId(packing.getId());

                // 保存商品对象
                packingProductDao.insertSelective(packingProduct);

                // 保存货物id、商品id（后面保存商品附件时候，需要指定哪个商品的附件）
                idMap.put(contractProduct.getId(), packingProduct.getId());
            }
        }

        //7. 根据购销合同，查询其下的所有附件
        ExtCproductExample extCproductExample = new ExtCproductExample();
        extCproductExample.createCriteria().andContractIdIn(contractIdList);
        List<ExtCproduct> extCproductList = extCproductDao.selectByExample(extCproductExample);
        //8. 【保存报运单的附件，数据来源于'购销合同的附件'】
        if (extCproductList != null && extCproductList.size() > 0) {
            for (ExtCproduct extCproduct : extCproductList) {
                // 创建报运单附件对象
                ExtEproduct extEproduct = new ExtEproduct();
                // 封装报运单附件对象
                BeanUtils.copyProperties(extCproduct, extEproduct);
                extEproduct.setId(UUID.randomUUID().toString());
                extEproduct.setPackingId(packing.getId());
                *//*
     * 设置商品id
     * 已知条件： 货物id  extCproduct.getContractProductId()
     * 求：      商品id
     *//*
                // 获取货物id
                String contractProductId = extCproduct.getContractProductId();
                // 根据货物id，获取商品id并设置到附件中
                extEproduct.setPackingProductId(idMap.get(contractProductId));

                // 保存报运单附件对象
                extEproductDao.insertSelective(extEproduct);
            }
        }

        //9. 【保存报运单】
        // 设置报运单的状态
        packing.setState(0);
        // 设置商品的数量 (5)
        packing.setProNum(contractProductList.size());
        // 设置商品附件的数量 (7)
        packing.setExtNum(extCproductList.size());
        // 最终，保存报运单
        packingDao.insertSelective(packing);
    }

    @Override
    public void update(Packing packing) {
        //1. 修改报运单
        packingDao.updateByPrimaryKeySelective(packing);

        //2. 修改报运单的商品
        List<PackingProduct> packingProducts = packing.getPackingProducts();
        if (packingProducts != null && packingProducts.size() > 0) {
            for (PackingProduct packingProduct : packingProducts) {
                // 修改报运单商品 (动态sql)
                packingProductDao.updateByPrimaryKeySelective(packingProduct);
            }
        }
    }
*/
    @Override
    public void delete(String id) {
        packingDao.deleteByPrimaryKey(id);
    }


}














